package com.example.demo.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@SpringBootConfiguration
public class SpringAsyncConfig implements AsyncConfigurer {

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程大小
        executor.setCorePoolSize(80);
        //最大线程数
        executor.setMaxPoolSize(120);
        //最大队列数量
        executor.setQueueCapacity(1000);
        //非核心线程的存活时间 秒 这里防止回写返回过慢时间定位5分钟
        executor.setKeepAliveSeconds(60 * 5);
        //线程前缀名
        executor.setThreadNamePrefix("taskExecutor-");
        //允许核心线程超时
        executor.setAllowCoreThreadTimeOut(true);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);  // 调度器shutdown被调用时等待当前被调度的任务完成
        executor.initialize();
        return executor;
    }


}
